package resman.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;

import resman.bean.CompBean;
import resman.bean.ResumeBean;
import resman.database.DatabaseHandler;
import resman.database.TransSession;
import resman.model.ActionServlet;

@SuppressWarnings("serial")
@WebServlet("/CompServlet")
public class CompServlet extends ActionServlet
{
	
	@Override
	protected void process(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException
	{
		TransSession tsession = DatabaseHandler.openSession(true);
		Session session = tsession.getSession();
		
		ResumeBean resume = getResume(request);

		int op = getOpParameter("op",  request);
		int id = getIntParameter("cid", request);
		
		CompBean comp;
		
		if (id != -1)
			comp = resume.getComp(id);
		else
			comp = new CompBean();
		
		if (op == ADD_OP)
		{
			comp.setProperties(request.getParameterMap());
			comp.setExchange(request.getParameter("exchange") != null);
			
			if (id == -1)
			{
				comp.setResume(resume);
				resume.getComps().add(comp);
				session.save(comp);
			}
			else
				session.merge(comp);
		}
		else
		{
			resume.getComps().remove(comp);
			session.delete(comp);
		}
		
		tsession.close();
		dispatchTo("views/comp_view.jsp", request, response);
	}

}
